﻿using System.Text.Json.Serialization.Metadata;
using DimensionsHelper.Common.Contracts.DataCollector;
using DimensionsHelper.Common.Contracts.DataCollector.Options;
using DimensionsHelper.Common.Contracts.Excel;
using DimensionsHelper.Common.Contracts.Services;
using DimensionsHelper.Common.Utils;

namespace DimensionsHelper.Client.ViewModels.DataCollector;

public partial class DataCollectorViewModel(IServiceProvider serviceProvider)
    : JsonLoaderViewModel<CollectorOptions>(serviceProvider)
{
    public static readonly string[] Writers =
    [
        "Aggregate",
        "Summary"
    ];


    [ObservableProperty]
    private string _outputFileName = string.Empty;


    [ObservableProperty]
    private string _writerName = Writers[0];


    public override string Section => "Excel数据收集器";

    protected override JsonTypeInfo<CollectorOptions> LoadingTypeInfo => ServiceJsonContext.Default.CollectorOptions;

    public override string HistoryJsonSettingName => "CollectorHistoricalSettings";


    [RelayCommand]
    private async Task SelectOutputFile()
    {
        if (await App.GetService<IFilePikerService>()!.SaveFileAsync(FileFilters.Excel) is not { Length: > 0 } directory)
        {
            return;
        }

        OutputFileName = directory;
    }


    public override void LoadOption(CollectorOptions source)
    {
    }

    public override bool TryWriteOption(CollectorOptions target)
    {
        return true;
    }


    protected override RunnableContainer GetRunnableContainer()
    {
        ICollector collector = ServiceProvider.GetRequiredService<ICollector>();
        collector.Writer = WriterName == Writers[0]
            ? ServiceProvider.GetRequiredService<IExcelAggregateWriter>()
            : ServiceProvider.GetRequiredService<IExcelSummaryWriter>();

        return new RunnableContainer<DataCollectorViewModel, ICollector, CollectorOptions>(this, collector,
            (dataCollector, serviceProvider, token) =>
            {
                if (string.IsNullOrEmpty(OutputFileName))
                {
                    dataCollector.ReportService?.Error(ProjectErrorMessages.ProjectExportPathIsNotConfig);
                    return;
                }

                // Input files
                List<CollectorInputFile> fileList =
                    serviceProvider.GetRequiredService<IndexFileListViewModel>().ToInputFiles();
                dataCollector.Collect(fileList, token);
                IExcelWorkbookOperator destination = serviceProvider.GetRequiredService<IExcelWorkbookOperator>();
                destination.Create(OutputFileName);
                dataCollector.Export(destination, token);
            });
    }
}